package com.itheima.Cookie.b_last;

import com.itheima.Cookie.Utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/lastTimeServlet")
public class LastTimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        //获取lastTimeCookie对象
        Cookie[] cookies = request.getCookies();

        //创建一个Cookie对象
        Cookie ck = CookieUtils.findCookieByName(cookies,"lastTimeCookie");


        //获取响应输出流对象
        PrintWriter pw = response.getWriter();

        //对ck进行判断
        if (ck==null){
            //说明是第一次访问
            pw.write("欢迎您首次访问本网页");
        }else {
            pw.write("欢迎您访问本网页,上次访问时间为:"+ck.getValue());
        }

        //不管是不是第一次访问都要设置时间
        Cookie cookie = new Cookie("lastTimeCookie",(new Date()).toLocaleString().replaceAll(" ",""));
        //设置持久化时间
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
